package com.study.score.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;

import com.study.course.domain.SysCourse;
import com.study.score.domain.LowScoreRecord;
import com.study.score.mapper.LowScoreRecordRepository;
import com.study.student.domain.SysStudent;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.study.common.annotation.Log;
import com.study.common.core.controller.BaseController;
import com.study.common.core.domain.AjaxResult;
import com.study.common.enums.BusinessType;
import com.study.score.domain.SysScore;
import com.study.score.service.ISysScoreService;
import com.study.common.utils.poi.ExcelUtil;
import com.study.common.core.page.TableDataInfo;

/**
 * 成绩查询Controller
 * 
 * @author rose
 * @date 2025-05-21
 */
@RestController
@RequestMapping("/score/score")
public class SysScoreController extends BaseController
{
    @Autowired
    private ISysScoreService sysScoreService;

    @Autowired
    private LowScoreRecordRepository lowScoreRecordRepository;

    /**
     * 查询成绩查询列表
     */
    /**
     * 查询成绩查询列表
     */
    @PreAuthorize("@ss.hasPermi('score:score:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysScore sysScore) {
        startPage();
        List<SysScore> list = sysScoreService.selectSysScoreList(sysScore);

        // 检查并存储分数 < 60 的记录
        for (SysScore score : list) {
            if (score.getScore() != null && score.getScore().compareTo(BigDecimal.valueOf(60)) < 0) {
                LowScoreRecord record = new LowScoreRecord();
                record.setStudentName(score.getStudentId());
                record.setCourseName(score.getCourseId());
                record.setScore(score.getScore());

                System.out.println("存储分数 < 60 的记录：" + record);

                try {
                    // 判断是否已存在该记录
                    Optional<LowScoreRecord> existing = lowScoreRecordRepository
                            .findByStudentNameAndCourseName(record.getStudentName(), record.getCourseName());

                    if (existing.isPresent()) {
                        System.out.println("⚠️ 该记录已存在，跳过插入: " + record);
                    } else {
                        lowScoreRecordRepository.save(record);
                        System.out.println("✅ 成功保存新记录到 MongoDB: " + record);
                    }
                } catch (Exception e) {
                    System.err.println("❌ 保存到 MongoDB 失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }

        }
        return getDataTable(list);
    }
    /**
     * 导出成绩查询列表
     */
    @PreAuthorize("@ss.hasPermi('score:score:export')")
    @Log(title = "成绩查询", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysScore sysScore)
    {
        List<SysScore> list = sysScoreService.selectSysScoreList(sysScore);
        ExcelUtil<SysScore> util = new ExcelUtil<SysScore>(SysScore.class);
        util.exportExcel(response, list, "成绩查询数据");
    }

    /**
     * 获取成绩查询详细信息
     */
    @PreAuthorize("@ss.hasPermi('score:score:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") String studentId)
    {
        return success(sysScoreService.selectSysScoreByStudentId(studentId));
    }

    /**
     * 新增成绩查询
     */
    @PreAuthorize("@ss.hasPermi('score:score:add')")
    @Log(title = "成绩查询", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysScore sysScore)
    {
        return toAjax(sysScoreService.insertSysScore(sysScore));
    }

    /**
     * 修改成绩查询
     */
    @PreAuthorize("@ss.hasPermi('score:score:edit')")
    @Log(title = "成绩查询", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysScore sysScore)
    {
        return toAjax(sysScoreService.updateSysScore(sysScore));
    }

    /**
     * 删除成绩查询
     */
    @PreAuthorize("@ss.hasPermi('score:score:remove')")
    @Log(title = "成绩查询", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable String[] studentIds)
    {
        return toAjax(sysScoreService.deleteSysScoreByStudentIds(studentIds));
    }

    /**
     * 查询学生列表（用于成绩管理）
     */
    @PreAuthorize("@ss.hasPermi('score:score:list')")
    @GetMapping("/student/list")
    public TableDataInfo listStudent() {
        startPage();
        List<SysStudent> list = sysScoreService.selectSysStudentList();
        return getDataTable(list);
    }

    /**
     * 查询课程列表（用于成绩管理）
     */
    @PreAuthorize("@ss.hasPermi('score:score:list')")
    @GetMapping("/course/list")
    public TableDataInfo listCourse(SysCourse sysCourse) {
        startPage();
        List<SysCourse> list = sysScoreService.selectSysCourseList(sysCourse);
        return getDataTable(list);
    }

}
